//
//  LoginHandle.m
//  LYYGame
//
//  Created by YUJIABO on 17/3/11.
//  Copyright © 2017年 YUJIABO. All rights reserved.
//

#import "LoginHandle.h"
#import "UserDao.h"
#import "HTTPRequest.h"
#import "JPUSHService.h"

@implementation LoginHandle
@synthesize userInfor = _userInfor;

static LoginHandle * instance = nil;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc]init];
    });
    
    return instance;
}

- (LYUserModel*)userInfor
{
    //不是登录状态 直接返回空值
    if (!self.isLoginStatus)
    {
        return nil;
    }
    else
    {
        if (!_userInfor)
        {
            _userInfor = [UserDao getUser];
        }
    }
    return _userInfor;
}

- (void)setUserInfor:(LYUserModel *)userInfor
{
    if (!userInfor) return;
    
    if (_userInfor!=userInfor)
    {
        _userInfor = userInfor;
    }
}

- (BOOL)isLoginStatus
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:kLoginStatus];
}

- (void)setIsLoginStatus:(BOOL)isLoginStatus
{
    NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];

    [userdefault setBool:isLoginStatus forKey:kLoginStatus];
    [userdefault synchronize];
}

- (void)setLoginToken:(NSString *)loginToken
{
    
    NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
    if (loginToken) {
        [userdefault setValue:loginToken forKey:kLoginToken];
        [userdefault synchronize];
    }
    
    
}

- (NSString*)loginToken
{
   return [[NSUserDefaults standardUserDefaults]valueForKey:kLoginToken];
}

- (void)saveUserInfoToLocal:(LYUserModel *)user
{
    [UserDao addUser:user];
}

- (void)loginOutDataHandle
{
     //清空用户信息表
     [UserDao cleanUserInfoTable];
    
     _userInfor = nil;
     self.isLoginStatus = NO;
     //发送退出登录的通知
     [[NSNotificationCenter defaultCenter]postNotificationName:kLogoutNotification object:nil];
     //清空token
     [self setLoginToken:@""];
}

- (void)loginSuccessDataHandle
{
    self.isLoginStatus = YES;
    //发送登录成功的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessNotification object:nil];
}
- (void)refreshMineDataNotification
{
   [[NSNotificationCenter defaultCenter] postNotificationName:kMeUpDataInfoNotification object:nil];
}

- (void)updateLocatUserInfo:(NSDictionary *)keyAndValues
{
    //不是字典不往下执行
    if (![keyAndValues isKindOfClass:[NSDictionary class]]||!keyAndValues)
    {
        return;
    }
    NSArray*keys = keyAndValues.allKeys;
    
    for (NSString*key in keys)
    {
        id value = [keyAndValues objectForKey:key];
        
        [_userInfor setValue:value forKey:key];
    }
    
    [self saveUserInfoToLocal:_userInfor];
}

// 个人资料是否完整的
+ (BOOL)isIntactOfUserInfo{
    LYUserModel *user =  [LoginHandle shareInstance].userInfor;
    BOOL isAuthen = [LoginHandle isAuthen];
    if (user.headIcon &&
        user.nickname &&
        user.qq       &&
        user.location &&
        user.address  &&
        isAuthen
        ) {
        //判断所有信息不为空,则发送通知，领取积分任务
    
        [[NSNotificationCenter defaultCenter] postNotificationName:kDidCompleteSavePersionInfoNotification object:self userInfo:@{@"type":@"persionInfo"}];
        
        return YES;
    }

    return NO;
}

// 是否为第三方登陆
+ (BOOL)isThirdPlatformLogin{
      //1 用户名注册 2 手机注册 3 邮箱注册 4 第三方登录
    if( [LoginHandle shareInstance].userInfor.regType == 4){
        return YES;
    }
    return NO;
}

// 是否完成认证
+ (BOOL)isAuthen{
    LYUserModel *user =  [LoginHandle shareInstance].userInfor;
    if (user.idcarNo && user.realName) {
        return true;
    }
    return false;
}

// 从服务器获取用户信息
+ (void)getUserInfoFromNetWork:(void(^)(LYUserModel *userInfo))successBlock{

    [HTTPRequest GET:kGetUserInfoUrl parameter:nil success:^(id resposeObject) {
        
        NSLog(@"用户信息:resposeObject%@",resposeObject);
        

        int result = [resposeObject[@"result"] intValue];
        switch (result) {
            case 0:
            case 401:
            case 402:{
                LYUserModel *model =[LYUserModel objectWithDic:resposeObject[@"user"]];
                
                NSString *jf = [NSString stringWithFormat:@"%@",resposeObject[@"jf"]];
                NSString *headIcon = [NSString stringWithFormat:@"%@",resposeObject[@"user"][@"headIcon"]];
                NSString *phone = [NSString stringWithFormat:@"%@",resposeObject[@"user"][@"phone"]];
                NSString *bindFlag = [NSString stringWithFormat:@"%@",resposeObject[@"bindFlag"]];
                model.bindFlag = bindFlag;
                model.jf = jf;
                model.headIcon = headIcon;
                model.phone = phone;
                //保存用户信息到本地
                [[LoginHandle shareInstance] updateLocatUserInfo:@{@"jf":jf}];
                [[LoginHandle shareInstance] updateLocatUserInfo:@{@"headIcon":headIcon}];
                [[LoginHandle shareInstance] updateLocatUserInfo:@{@"bindFlag":bindFlag}];
                [[LoginHandle shareInstance] updateLocatUserInfo:@{@"phone":phone}];
                [LH saveUserInfoToLocal:model];
                //修改内存中用户信息
                LH.userInfor = model;
                
                if (successBlock) {
                    successBlock(model);
                }

            }
                break;
            case 270:{
                [MBProgressHUD LY_ShowError:LYLocalizedString(resposeObject[@"msg"]) time:2.0];
            }
                break;
                
            default:
                [MBProgressHUD LY_ShowError:LYLocalizedString(resposeObject[@"msg"]) time:2.0];
                break;
        }
        
    } failure:^(NSError *error) {
        NSLog(@"error%@",error);
        [MBProgressHUD LY_ShowError:LYLocalizedString(kNoNetworkTips) time:2.0];
     
    }];
}


+ (void)JPushConfig{
    //JPush设置别名
    [JPUSHService setAlias:[NSString stringWithFormat:@"user_%@",LH.userInfor.userId] callbackSelector:nil object:nil];
}

+ (BOOL)isBindingPhone{
    if ([[LoginHandle shareInstance].userInfor.phone  isEqual:@"(null)"]) {
        return NO;
    }
    return YES;
}
@end
